﻿#include "SDLRenderYUVWindow.h"
#include <QFile>
#include <QFileDialog>
#include <QDebug>
#include "utils/SDLRenderUtil.h"
#include <mutex>

SDLRenderYUVWindow::SDLRenderYUVWindow(QWidget* parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	this->setWindowTitle("SDL播放YUV文件");
	this->setFixedSize(QSize(400, 480));
	setAttribute(Qt::WA_DeleteOnClose, true);  // 关闭时自动销毁窗口
	binaryFileReader = BinaryFileReader::Create();
}

void SDLRenderYUVWindow::choiceYUV420PFile()
{
	mWidth = ui.labelVideo->width();
	mHeight = ui.labelVideo->height();
	QString filter = "RGB 文件 (*.*);;所有文件 (*.*)";
	// 打开文件选择对话框，选择单个文件
	QString filePath = QFileDialog::getOpenFileName(this, "选择 RGB 文件", "", filter);
	binaryFileReader->filename = filePath.toStdString();
	binaryFileReader->width = mWidth;
	binaryFileReader->height = mHeight;
	binaryFileReader->Init();

	SDLRenderUtil::Get()->width = mWidth;
	SDLRenderUtil::Get()->height = mHeight;
	SDLRenderUtil::Get()->winId = (void*)ui.labelVideo->winId();
	SDLRenderUtil::Get()->PIX_FMT = 3;
	SDLRenderUtil::Get()->Init();

	// 创建并启动后台线程
	renderThread = std::make_unique<std::thread>(&SDLRenderYUVWindow::RenderVideo, this);
	/*renderThread([=] {
		char* data = new  char[mWidth * mHeight * 1.5];
		for (;;) {
			SDLRenderUtil::Get()->isEventQuit();
			bool ret = BinaryFileReader::Get()->ReadYUV420P(data);
			if (!ret) {
				break;
			}
			SDLRenderUtil::Get()->Render(data);
			std::this_thread::sleep_for(33ms);
		}
		delete data;
		});*/
		//renderThread.detach();//线程分离
		//renderThread.join();//等待子线程结束
}

void SDLRenderYUVWindow::RenderVideo()
{
	char* data = new  char[mWidth * mHeight * 1.5];
	for (;;) {
		if (!isRunning)break;
		SDLRenderUtil::Get()->isEventQuit();
		bool ret = binaryFileReader->ReadYUV420P(data);
		if (!ret) {
			break;
		}
		SDLRenderUtil::Get()->Render(data);
		std::this_thread::sleep_for(33ms);
	}
	if (data) {
		delete data;
	}
	qDebug() << "已释放了data内存";
}

void SDLRenderYUVWindow::closeEvent(QCloseEvent* event) {
	isRunning = false;
	// 等待线程结束
	if (renderThread && renderThread->joinable()) {
		renderThread->join();
	}
	binaryFileReader->Close();
	SDLRenderUtil::Get()->Close();
	event->accept();  // 接受关闭事件（允许关闭）
	qDebug() << "窗口已关闭";
}

SDLRenderYUVWindow::~SDLRenderYUVWindow()
{
	qDebug() << "执行了SDLRenderYUVWindow的析构函数";
}
